package com.lw.leetcode.str.b;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 面试题 05.02. 二进制数转字符串
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/11 20:52
 */
public class PrintBin {

    public static void main(String[] args) {
        PrintBin test = new PrintBin();

        // "0.101"
//        double num = 0.625D;

        // "0.101"
        double num = 0.1D;

        String s = test.printBin(num);
        System.out.println(s);
    }

    public String printBin(double num) {

        BigDecimal decimal = BigDecimal.valueOf(num);
        Map<BigDecimal, Integer> map = new HashMap<>();
        StringBuilder sb = new StringBuilder("0.");
        BigDecimal z = BigDecimal.ZERO;
        BigDecimal o = BigDecimal.ONE;
        BigDecimal t = BigDecimal.valueOf(2);
        while (decimal.compareTo(z) != 0) {
            if (map.containsKey(decimal)) {
                return "ERROR";
            }
            map.put(decimal, 1);
            decimal = decimal.multiply(t);
            if (decimal.compareTo(o) >= 0) {
                sb.append('1');
                decimal = decimal.subtract(o);
            } else {
                sb.append('0');
            }
        }
        return sb.toString();
    }

}
